module.exports = {
  canvas,
}

function canvas(data) {
  let ctx = wx.createCanvasContext(data.canvasId);
  var systemInfo = wx.getSystemInfoSync();
  var windowWidth = systemInfo.windowWidth;
  var windowHeight = systemInfo.windowHeight;

  // 设置ctx到data
  data.ctx = ctx;
  // 设置响应转换
  data.getSize = (new UIToReality(windowWidth)).transitionUI;
  // 设置画布的宽高到data
  data.canvasWidth = data.getSize(700);
  data.canvasHeight = data.getSize(900);

  // 画板改变
  if (data.changeSize) data.changeSize({
    width: data.canvasWidth,
    height: data.canvasHeight,
  });

  // 保存为图片
  this.canvasToTempFilePath = function(callback) {
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      canvasId: data.canvasId,
      success: function(res) {
        if (callback) {
          callback(res.tempFilePath);
        } else {
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success(res) {
              wx.showToast({
                title: '保存成功',
                duration: 1000
              })
            }
          })
        }
      }
    })
  }

  this.canvasData=function(d){
    data.data = d;
    // 头像
    canvaImghead(data);
    // 昵称
    canvaNickname(data);
    // 时间
    canvaTime(data);
    // 二维码
    canvaQCode(data);
    // 标题
    canvaTitle(data);
    // 标签类型
    canvaLable(data);
    // 地址
    canvaAddress(data);
    // 排名
    canvaRank(data);
  }

  // 填充背景色及背景大小
  canvaBg(data);
}

// 排名
function canvaRank(data) {
  var ctx = data.ctx;
  var tempData = {
    rank: data.data.rank,
    marginLeft: data.canvasWidth / 2,
    marginTop: data.getSize(226 + 180),
    fontSize: data.getSize(70)
  }

  if (!tempData.rank) return;

  // 字符串数组
  let arr = getFontsMetrics(data, tempData.rank, 400);
  // 当前需要渲染几行
  let line = 1;
  for (let i = 0; i < arr.length; i++) {
    if (i < line) {
      let text = i == line - 1 ? arr[i].textd : arr[i].text;
      ctx.setTextAlign('left')
      ctx.setTextBaseline('top')
      ctx.setFillStyle('#332F36')
      ctx.setTextAlign('center')
      ctx.setFontSize(tempData.fontSize)
      ctx.fillText(text, tempData.marginLeft, tempData.marginTop)
      ctx.draw(true, function () {
        console.log('地址绘制完毕')
      })
      tempData.marginTop += data.getSize(40);
    }
  }
}

// 地址
function canvaAddress(data) {
  var ctx = data.ctx;
  var tempData = {
    address: data.data.address,
    marginLeft: data.canvasWidth / 2,
    marginTop: data.getSize(146 + 180),
    fontSize: data.getSize(26)
  }

  if (!tempData.address) return;

  // 字符串数组
  let arr = getFontsMetrics(data, tempData.address, 400);
  // 当前需要渲染几行
  let line = 1;
  for (let i = 0; i < arr.length; i++) {
    if (i < line) {
      let text = i == line - 1 ? arr[i].textd : arr[i].text;
      ctx.setTextAlign('left')
      ctx.setTextBaseline('top')
      ctx.setFillStyle('#332F36')
      ctx.setTextAlign('center')
      ctx.setFontSize(tempData.fontSize)
      ctx.fillText(text, tempData.marginLeft, tempData.marginTop)
      ctx.draw(true, function () {
        console.log('地址绘制完毕')
      })
      tempData.marginTop += data.getSize(40);
    }
  }
}

// 标签类型
function canvaLable(data) {
  var ctx = data.ctx;
  var tempData = {
    lable: data.data.lable,
    marginLeft: data.canvasWidth / 2,
    marginTop: data.getSize(96+180),
    fontSize: data.getSize(26)
  }

  if (!tempData.lable) return;

  // 字符串数组
  let arr = getFontsMetrics(data, tempData.lable, 700);
  // 当前需要渲染几行
  let line = 1;
  for (let i = 0; i < arr.length; i++) {
    if (i < line) {
      let text = i == line - 1 ? arr[i].textd : arr[i].text;
      ctx.setTextAlign('left')
      ctx.setTextBaseline('top')
      ctx.setFillStyle('#332F36')
      ctx.setTextAlign('center')
      ctx.setFontSize(tempData.fontSize)
      ctx.fillText(text, tempData.marginLeft, tempData.marginTop)
      ctx.draw(true, function () {
        console.log('标签绘制完毕')
      })
      tempData.marginTop += data.getSize(40);
    }
  }
}

// 标题
function canvaTitle(data) {
  var ctx = data.ctx;
  var tempData = {
    title: data.data.title,
    marginLeft: data.canvasWidth / 2,
    marginTop: data.getSize(216),
    fontSize: data.getSize(40)
  }

  if (!tempData.title) return;

  // 字符串数组
  let arr = getFontsMetrics(data, tempData.title, 220);
  // 当前需要渲染几行
  let line = 1;
  for (let i = 0; i < arr.length; i++) {
    if (i < line) {
      let text = i == line - 1 ? arr[i].textd : arr[i].text;
      ctx.setTextAlign('left')
      ctx.setTextBaseline('top')
      ctx.setFillStyle('#332F36')
      ctx.setTextAlign('center')
      ctx.setFontSize(tempData.fontSize)
      ctx.fillText(text, tempData.marginLeft, tempData.marginTop)
      ctx.draw(true, function () {
        console.log('标题绘制完毕')
      })
      tempData.marginTop += data.getSize(40);
    }
  }
}

// 二维码
function canvaQCode(data) {
  var ctx = data.ctx;
  var canvasWidth = data.canvasWidth;
  var tempData = {
    code: data.data.code,
    width: data.getSize(100),
    height: data.getSize(100),
    marginRight: data.getSize(110),
    marginTop: data.getSize(640),
  }

  if (!tempData.code) return;
  
  ctx.drawImage(tempData.code, canvasWidth - tempData.width - tempData.marginRight, tempData.marginTop, tempData.width, tempData.height)
  ctx.restore()
  ctx.draw(true, function () {
    console.log('二维码绘制完毕')
  })
}

// 时间
function canvaTime(data) {
  var ctx = data.ctx;
  var tempData = {
    cardDays: data.data.cardDays,
    marginLeft: data.getSize(230),
    marginTop: data.getSize(702),
    fontSize: data.getSize(26)
  }

  if (!tempData.cardDays) return;

  ctx.setTextAlign('left')
  ctx.setTextBaseline('top')
  ctx.setFillStyle('#1F1F1F')
  ctx.setFontSize(tempData.fontSize)
  ctx.fillText(tempData.cardDays, tempData.marginLeft, tempData.marginTop)
  ctx.draw(true, function () {
    console.log('时间绘制完毕')
  })
}

// 昵称
function canvaNickname(data) {
  var ctx = data.ctx;
  var tempData = {
    nickName: data.data.nickName,
    marginLeft: data.getSize(230),
    marginTop: data.getSize(658),
    fontSize: data.getSize(30)
  }

  if (!tempData.nickName) return;

  // 字符串数组
  let arr = getFontsMetrics(data, tempData.nickName, 500);
  // 当前需要渲染几行
  let line = 1;
  for (let i = 0; i < arr.length; i++) {
    if (i < line) {
      let text = i == line - 1 ? arr[i].textd : arr[i].text;
      ctx.setTextAlign('left')
      ctx.setTextBaseline('top')
      ctx.setFillStyle('#332F36')
      ctx.setFontSize(tempData.fontSize)
      ctx.fillText(text, tempData.marginLeft, tempData.marginTop)
      ctx.draw(true, function () {
        console.log('呢称绘制完毕')
      })
      tempData.marginTop += data.getSize(40);
    }
  }
}

// 头像
function canvaImghead(data) {
  var ctx = data.ctx;
  var tempData = {
    headimg: data.data.headimg,
    width: data.getSize(100),
    height: data.getSize(100),
    marginLeft: data.getSize(110),
    marginTop: data.getSize(640),
  }

  if (!tempData.headimg) return;

  ctx.save();
  ctx.arc(tempData.width / 2 + tempData.marginLeft, tempData.height / 2 + tempData.marginTop, tempData.width / 2, 0, 2 * Math.PI)
  ctx.fill()
  ctx.clip()
  ctx.drawImage(tempData.headimg, tempData.marginLeft, tempData.marginTop, tempData.width, tempData.height)
  ctx.restore()
  ctx.draw(true, function () {
    console.log('头像绘制完毕')
  })
}

// 填充背景色及背景大小
function canvaBg(data) {
  var ctx = data.ctx;
  var transitionUI = data.transitionUI;
  var canvasWidth = data.canvasWidth;
  var canvasHeight = data.canvasHeight;
  var bgImg = data.data.bgImg;

  if (!bgImg) return;

  // 填充背景颜色
  ctx.drawImage(bgImg, 0, 0, canvasWidth, canvasHeight)
  ctx.draw(true,function(){
    console.log('背景绘制完毕')
  })
}

/**
 * 对应字符串通过指定的长度分成多个数组
 * @param   data    Object
 * @param   value   String        需要截取的字符串
 * @param   width   Number        当前位置插入字符串的最长长度（响应式，单位：rpx）
 * @return          ObjectArray   返回字符串截取json
 */
function getFontsMetrics(data, value, width) {
  var ctx = data.ctx;
  let metrics = null,
    arr = [],
    temp = "";
  for (let i = 0; i < value.length; i++) {
    metrics = ctx.measureText(temp);
    if (metrics.width >= data.getSize(width)) {
      let textd = temp.slice(0, temp.length - 1) + "...";
      arr.push({
        text: temp,
        textd,
      });
      temp = value[i];
    } else {
      temp += value[i];
    }
    if (i == value.length - 1) {
      let textd = temp;

      if (ctx.measureText(temp).width > data.getSize(width)) {
        textd = temp.slice(0, temp.length - 1) + "...";
      }

      arr.push({
        text: temp,
        textd,
      });
    }
  }

  return arr;
}

// 响应式转换对象(ui750转实际px)
function UIToReality(windowWidth) {

  this.transitionUI = function(size = 750) {
    return size / 750 * windowWidth;
  }

}